package com.health.viewscontrols;

import java.util.ArrayList;
import java.util.List;

import com.health.R;
import com.health.db.FDbManager;
import com.health.tablebean.BTDevice;
import com.novabluetooth.adapter.BlueToothDeviceAdapter;
import com.novabluetooth.services.BluetoothConstant;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
//@Deprecated
public class BluetoothDeviceBindActivity extends Activity
		implements OnItemClickListener, OnItemLongClickListener, android.view.View.OnClickListener {
	/* 取得默认的蓝牙适配器 */
	private BluetoothAdapter _bluetooth = BluetoothAdapter.getDefaultAdapter();
	/* 用来存储搜索到的蓝牙设备 */
	private List<BluetoothDevice> _devices = new ArrayList<BluetoothDevice>();
	/* 是否完成搜索 */
	private List<BTDevice> scanList = new ArrayList<BTDevice>();
	private List<BTDevice> savedList = new ArrayList<BTDevice>();
	FDbManager fdbmanger = NovaApplication.fdbmanger;
	private ListView saveListView;
	private ListView scanListView;
	private BlueToothDeviceAdapter savedAdapter;
	private Thread searchThread;
	private BlueToothDeviceAdapter scanAdapter;
	private Button fanhui;//390000
	private Button save;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.bluetooth_sbcl_bind_discovery);
		saveListView = (ListView) findViewById(R.id.bluetooth_saved_lv);
		scanListView = (ListView) findViewById(R.id.bluetooth_scan_lv);
		fanhui = (Button) findViewById(R.id.btn_back);
		fanhui.setOnClickListener(this);
		save = (Button) findViewById(R.id.btn_up);

		View scanHead = View.inflate(this, R.layout.bluetooth_sbcl_bind_head, null);
		View saveHead = View.inflate(this, R.layout.bluetooth_sbcl_bind_head, null);
		setHeadTitle("已经绑定的设备", saveHead);
		setHeadTitle("搜索到的设备", scanHead);
		saveListView.addHeaderView(saveHead);
		scanListView.addHeaderView(scanHead);
		scanListView.setOnItemClickListener(this);
		saveListView.setOnItemClickListener(this);
		saveListView.setOnItemLongClickListener(this);
		showList();
		Log.i("asdf", "注册用以接收到已搜索到的蓝牙设备的receiver");
		// 注册用以接收到已搜索到的蓝牙设备的receiver
		IntentFilter mFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
		registerReceiver(mReceiver, mFilter);
		Log.i("asdf", "注册搜索完时的receiver");
		// 注册搜索完时的receiver
		mFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
		registerReceiver(mReceiver, mFilter);
		if (!_bluetooth.isEnabled()) {
			_bluetooth.enable();
		}
		Log.i("asdf", "// 开始搜索蓝牙设备,搜索到的蓝牙设备通过广播返回");
		// 开始搜索蓝牙设备,搜索到的蓝牙设备通过广播返回
		setProgressBarIndeterminateVisibility(true);
		_bluetooth.startDiscovery();
	}

	private void setHeadTitle(String title, View head) {
		TextView tv = (TextView) head.findViewById(R.id.bluetooth_head_tv);
		tv.setText(title);
	}

	boolean mScanning;
	private static final long SCAN_PERIOD = 60000;

	@Override
	protected void onDestroy() {
		unregisterReceiver(mReceiver);
		super.onDestroy();
	}

	private void showList() {
		savedList = fdbmanger.findAllBT(BTDevice.class);
		savedAdapter = new BlueToothDeviceAdapter(this, savedList);
		saveListView.setAdapter(savedAdapter);

		scanAdapter = new BlueToothDeviceAdapter(this, scanList);
		scanListView.setAdapter(scanAdapter);

	}

	/* 显示列表 */
	protected void showScanDevices() {
		for (int i = 0, size = _devices.size(); i < size; ++i) {
			BluetoothDevice d = _devices.get(i);
			BTDevice device = new BTDevice();
			try {
				Log.i("nova", d.getName());
			} catch (Exception e) {
				// TODO: handle exception
			}

			String novaName = BluetoothConstant.getNovaDevice(d.getName());
			if (TextUtils.isEmpty(novaName)) {
				return;
			}
			device.setName(novaName);
			device.setMacAddress(d.getAddress());
			if (!scanList.contains(device)) {
				scanList.add(device);
				scanAdapter.notifyDataSetChanged();
			}
		}
	}

	private boolean isSavedDevice(BTDevice device, List<BTDevice> list) {
		boolean isSaved = false;
		if (list.size() < 0) {
			return isSaved;
		}
		for (BTDevice btDevice : list) {
			if (btDevice.equals(device)) {
				isSaved = true;
				break;
			}
		}
		return isSaved;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		if (position == 0) {
			return;
		}
		if (parent.equals(saveListView)) {
			BTDevice savedDevice = savedList.get(position - 1);
		} else if (parent.equals(scanListView)) {
			getNewSavedList();
			BTDevice device = scanList.get(position - 1);
			if (!isSavedDevice(device, savedList)) {
				fdbmanger.saveBT(device);
				savedList.add(device);
				savedAdapter.setInfoList(savedList);
				savedAdapter.notifyDataSetChanged();
				Toast.makeText(this, "已绑定设备：" + device.getName(), 0).show();
			} else {
				Toast.makeText(this, "设备已存在", 0).show();
			}
		}

	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {

		if (position != 0) {

			new AlertDialog.Builder(this).setTitle("确认删除").setMessage("确定删除所选项吗？")
					.setPositiveButton("删除", new OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							getNewSavedList();
							BTDevice btDevice = savedList.get(position - 1);
							fdbmanger.deleteBT(btDevice);
							savedList.remove(btDevice);
							savedAdapter.setInfoList(savedList);
							savedAdapter.notifyDataSetChanged();

						}
					}).setNegativeButton("取消", null).show();
		}

		return true;
	}

	private void getNewSavedList() {
		savedList = fdbmanger.findAllBT(BTDevice.class);
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		if (id == R.id.btn_back) {
			finish();
		} else {
		}

	}

	private BroadcastReceiver mReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub

			String action = intent.getAction();
			Log.i("asdf", "获得已经搜索到的蓝牙设备");
			// 获得已经搜索到的蓝牙设备
			if (action.equals(BluetoothDevice.ACTION_FOUND)) {
				BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				if (device.getName() != null) {
					/* 将结果添加到列表中 */
					_devices.add(device);
					/* 显示列表 */
					System.out.println(device.getName() + "*****************");
					runOnUiThread(new Runnable() {
						public void run() {
							showScanDevices();
						}
					});
				}
				// 搜索完成
			} else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
				setProgressBarIndeterminateVisibility(false);
			}
		}

	};

}
